package com.iwe.crm.workbench.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.github.pagehelper.PageHelper;
import com.iwe.crm.base.bean.ResultVo;
import com.iwe.crm.base.exception.CrmEnum;
import com.iwe.crm.base.exception.CrmException;
import com.iwe.crm.base.util.CommonUtil;
import com.iwe.crm.base.util.DateUtil;
import com.iwe.crm.user.bean.User;
import com.iwe.crm.user.mapper.UserMapper;
import com.iwe.crm.workbench.bean.Activity;
import com.iwe.crm.workbench.bean.ActivityRemark;
import com.iwe.crm.workbench.mapper.ActivityMapper;
import com.iwe.crm.workbench.mapper.ActivityRemarkMapper;
import com.iwe.crm.workbench.service.ActivityService;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ActivityRemarkMapper activityRemarkMapper;

    @Override
    public List<Activity> queryList(int page,int pageSize,Activity activity) {
        Example example = new Example(Activity.class);
        Example.Criteria criteria = example.createCriteria();

        //市场活动名称模糊查询
        if(StrUtil.isNotEmpty(activity.getName())){
            criteria.andLike("name","%" + activity.getName() + "%");
        }
        //所有者模糊查询
        if(StrUtil.isNotEmpty(activity.getOwner())){
            //先根据用户姓名模糊查询用户
            Example example1 = new Example(User.class);
            example1.createCriteria().andLike("name","%" + activity.getOwner() + "%");
            List<User> users = userMapper.selectByExample(example1);

            List<String> uids = new ArrayList<>();
            //取出用户的主键
            for (User user : users) {
                uids.add(user.getId());
            }
            //查询市场活动
            criteria.andIn("owner",uids);
        }

        //>开始时间查询
        if(StrUtil.isNotEmpty(activity.getStartDate())){
            criteria.andGreaterThanOrEqualTo("startDate",activity.getStartDate());
        }
        //<结束时间查询
        if(StrUtil.isNotEmpty(activity.getEndDate())){
            criteria.andLessThanOrEqualTo("endDate",activity.getEndDate());
        }

        //等同于limit a,b
        PageHelper.startPage(page,pageSize);
        //查询的市场活动
        List<Activity> activities =  activityMapper.selectByExample(example);
        for (Activity activity1 : activities) {
            //所有者外键,就是用户主键
            String owner = activity1.getOwner();
            //根据用户主键查询用户
            User user = userMapper.selectByPrimaryKey(owner);
            activity1.setOwner(user.getName());
        }
        return activities;
    }

    @Override
    public ResultVo saveOrUpdate(Activity activity, User user) {
        ResultVo resultVo = new ResultVo();
        if(activity.getId() != null){
            //修改
            user.setEditBy(user.getName());
            user.setEditTime(DateUtil.dateToString(new Date()));
            int count = activityMapper.updateByPrimaryKeySelective(activity);
            if(count == 0){
                throw new CrmException(CrmEnum.ACTIVITY_UPDATE);
            }
            resultVo.setMessage("修改市场活动成功");
        }else{
            user.setCreateBy(user.getName());
            //添加
            String uuid = CommonUtil.uuid();
            activity.setId(uuid);
            activity.setCreateTime(DateUtil.dateToString(new Date()));
            int count = activityMapper.insertSelective(activity);

            if(count == 0){
                throw new CrmException(CrmEnum.ACTIVITY_ADD);
            }
            resultVo.setMessage("添加市场活动成功");
        }
        resultVo.setOk(true);
        return resultVo;
    }

    @Override
    public Activity queryById(String id) {
        return activityMapper.selectByPrimaryKey(id);
    }


    @Override
    public void deleteBatch(String ids) {
        List<String> aids = Arrays.asList(ids.split(","));
        Example example = new Example(Activity.class);

        example.createCriteria().andIn("id",aids);

        activityMapper.deleteByExample(example);
    }

    @Override
    public void saveRemark(ActivityRemark activityRemark,User user) {
        activityRemark.setImg(user.getImg());
        activityRemark.setCreateBy(user.getName());
        activityRemark.setCreateTime(DateUtil.dateToString(new Date()));
        //主键
        activityRemark.setId(CommonUtil.uuid());

        activityRemarkMapper.insertSelective(activityRemark);
    }

    @Override
    public Activity toDetail(String id) {
        //1、先查询市场活动数据
        Activity activity = queryById(id);

        //2、查询市场活动对应的备注数据
        ActivityRemark activityRemark = new ActivityRemark();
        activityRemark.setActivityId(id);
        List<ActivityRemark> activityRemarks =
                activityRemarkMapper.select(activityRemark);
        //判断详情页有没有备注数据
        if(activityRemarks.size() > 0){
            activity.setActivityRemarks(activityRemarks);
        }
        return activity;
    }

    @Override
    public void deleteRemark(String id) {
        activityRemarkMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void updateRemark(ActivityRemark activityRemark,User user) {
        activityRemark.setEditBy(user.getName());
        activityRemark.setEditTime(DateUtil.dateToString(new Date()));
        activityRemark.setEditFlag("1");

        activityRemarkMapper.updateByPrimaryKeySelective(activityRemark);
    }

    @Override
    public ExcelWriter exportExcel(ExcelWriter writer) {
        Example example = new Example(Activity.class);
        //把所有属性封装到Map中
        Map<String, EntityColumn> propertyMap = example.getPropertyMap();
        List<Activity> activities = activityMapper.selectByExample(example);
        writer.merge(propertyMap.size() - 1, "市场活动统计图表");

        // 定义单元格背景色
        StyleSet style = writer.getStyleSet();
        // 第二个参数表示是否也设置头部单元格背景
        style.setBackgroundColor(IndexedColors.RED, false);
        writer.write(activities, true);
        return writer;
    }
}
